﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common.Service;
using System.Collections;
using OC.Common.Entity;

namespace OC
{
    public partial class RoleGroupRule : System.Web.UI.Page
    {
        OC.Common.Interface.IDictionary _dictionaryService;


        public OC.Common.Interface.IDictionary DictionaryService
        {
            get
            {
                if (_dictionaryService == null)
                {
                    _dictionaryService = ServiceContainer.GetService<OC.Common.Interface.IDictionary>();
                }
                return _dictionaryService;
            }
            set { _dictionaryService = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitUserGroupView("USERGROUP", tvUserGroup);
                InitDropDownList();
                InitUserGroupView(ddlRoleList.SelectedValue, tvRoleItem);
                tvUserGroup.ExpandDepth = 1;
                tvRoleItem.ExpandDepth = 1;
                tvRoleItem.Attributes.Add("onclick", "postBackObject()");
            }
        }
        private void InitDropDownList()
        {
            IList roleList = DictionaryService.GetListByDictionaryType("DictionaryLogic_GetListByDictionaryType", "DropDownListRole");
            foreach (DictionaryEntity item in roleList)
            {
                ddlRoleList.Items.Add(new ListItem(item.CN_NAME, item.EXT20));
            }

        }
        private void InitUserGroupView(string type, TreeView tv)
        {
            IList userGroups = DictionaryService.GetListByDictionaryType("DictionaryLogic_GetListByDictionaryType", type);

            foreach (DictionaryEntity item in userGroups)
            {
                if (item.PARENT_DICTIONARY_ID.Trim() == "0")//先找到根节点
                {
                    TreeNode tn = new TreeNode();
                    tn.Text = item.CN_NAME;
                    tn.Value = item.DICTIONARY_ID;
                    GetChildNodeByList(userGroups, item.DICTIONARY_ID, tn);
                    tv.Nodes.Add(tn);
                }
            }
            //tv.ExpandDepth = 1;
        }

        /// <summary>
        /// 根据ID在查询到的组织数据中轮询查找它的子节点
        /// </summary>
        /// <param name="structure"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private TreeNode GetChildNodeByList(IList structure, string id, TreeNode ptn)
        {
            foreach (DictionaryEntity item in structure)
            {
                if (id == item.PARENT_DICTIONARY_ID)
                {
                    TreeNode tn = new TreeNode();
                    tn.Text = item.CN_NAME;
                    tn.Value = item.DICTIONARY_ID;
                    ptn.ChildNodes.Add(tn);
                    foreach (DictionaryEntity cItem in structure)
                    {
                        if (item.DICTIONARY_ID == cItem.PARENT_DICTIONARY_ID)
                        {
                            TreeNode ctn = new TreeNode();
                            ctn.Text = cItem.CN_NAME;
                            ctn.Value = cItem.DICTIONARY_ID;
                            tn.ChildNodes.Add(ctn);
                        }
                    }
                }
            }
            return ptn;
        }
        protected void tvUserGroup_SelectedNodeChanged(object sender, EventArgs e)
        {
            GetUserGroupRule(true);
        }

        private void GetUserGroupRule(bool isUpdate)//参数：是否需要更新ViewState["DictionaryRelationList"]
        {
            int count = tvRoleItem.CheckedNodes.Count - 1;
            for (int i = count; i >= 0; i--)
            {
                tvRoleItem.CheckedNodes[i].Checked = false;
            }
            if (isUpdate)
            {
                ViewState["DictionaryRelationList"] = null;
            }
            foreach (TreeNode node in tvRoleItem.Nodes)
            {
                if (node.ChildNodes.Count > 0)
                {
                    SetRoleItemIsCheck(node, isUpdate);
                }
            }
        }

        private void SetRoleItemIsCheck(TreeNode pNode, bool isUpdate)
        {
            List<DictionaryRelationEntity> DictionaryRelationList = new List<DictionaryRelationEntity>();
            string dicID = tvUserGroup.SelectedValue;
            string meunType = ddlRoleList.SelectedValue;
            IList dicRelations = DictionaryService.GetDictionaryRelationByRelation_Type("ROLE", dicID);
            if (isUpdate)
            {
                foreach (DictionaryRelationEntity item in dicRelations)
                {

                    DictionaryRelationEntity dicRelation = NewDictionaryRelationEntity(item.DESTINATION_DICTIONARY_ID, item.SOURCE_DICTIONARY_ID);
                    DictionaryRelationList.Add(dicRelation);
                    CheckDicRelationItem(pNode, isUpdate, item);
                }
            }
            if (isUpdate)
            {
                ViewState["DictionaryRelationList"] = DictionaryRelationList;
            }
            else
            {
                if (ViewState["DictionaryRelationList"] != null)
                {
                    List<DictionaryRelationEntity> DictionaryRelation = ViewState["DictionaryRelationList"] as List<DictionaryRelationEntity>;
                    foreach (DictionaryRelationEntity item in DictionaryRelation)
                    {
                        CheckDicRelationItem(pNode, isUpdate, item);
                    }
                }
            }
        }

        private void CheckDicRelationItem(TreeNode pNode, bool isUpdate, DictionaryRelationEntity item)
        {
            foreach (TreeNode node in pNode.ChildNodes)
            {
                if (node.Value == item.DESTINATION_DICTIONARY_ID)
                {
                    node.Checked = true;
                }
                if (node.ChildNodes.Count > 0)
                {
                    SetRoleItemIsCheck(node, isUpdate);
                }
            }
        }

        protected void tvUserGroup_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
        {
            TreeNode tn = e.Node;
            if (tn.ChildNodes.Count > 0)
            {
                foreach (TreeNode item in tn.ChildNodes)
                {
                    if (item.ChildNodes.Count <= 0)
                    {
                        IList dicEntitys = DictionaryService.GetList(item.Value);
                        foreach (DictionaryEntity dics in dicEntitys)
                        {
                            TreeNode ctn = new TreeNode();
                            ctn.Text = dics.CN_NAME;
                            ctn.Value = dics.DICTIONARY_ID;
                            item.ChildNodes.Add(ctn);
                        }
                    }
                }
            }
        }

        protected void ddlRoleList_SelectedIndexChanged(object sender, EventArgs e)
        {
            tvRoleItem.Nodes.Clear();
            InitUserGroupView(ddlRoleList.SelectedValue, tvRoleItem);
            tvRoleItem.ExpandAll();
            GetUserGroupRule(false);//参数：是否需要更新ViewState["DictionaryRelationList"]
        }


        protected void tvRoleItem_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        {
            if (string.IsNullOrEmpty(tvUserGroup.SelectedValue))
            {
                return;
            }
            string desID = e.Node.Value;
            string sourceID = tvUserGroup.SelectedValue;
            List<DictionaryRelationEntity> DictionaryRelationList = ViewState["DictionaryRelationList"] as List<DictionaryRelationEntity>;
            DictionaryRelationEntity dicRelationEntity = DictionaryRelationList.Find(delegate(DictionaryRelationEntity entity)
                                    {
                                        if (entity.SOURCE_DICTIONARY_ID == sourceID && entity.DESTINATION_DICTIONARY_ID == desID)
                                        {
                                            return true;
                                        }
                                        return false;
                                    });
            if (!e.Node.Checked && dicRelationEntity != null)//没选中但存在该项,需要删除
            {
                DictionaryRelationList.Remove(dicRelationEntity);
            }
            else if (e.Node.Checked && dicRelationEntity == null)//选中并且集合中不存在该项,需要添加
            {
                DictionaryRelationEntity dicRelation = NewDictionaryRelationEntity(desID, sourceID);
                DictionaryRelationList.Add(dicRelation);
            }
            else if (e.Node.Checked && dicRelationEntity != null)//选中存在该项,不需要进行操作
            {

            }
            else if (!e.Node.Checked && dicRelationEntity == null)//没选中不存在该项,不需要进行操作
            {

            }

        }

        private static DictionaryRelationEntity NewDictionaryRelationEntity(string desID, string sourceID)
        {
            DictionaryRelationEntity dicRelation = new DictionaryRelationEntity();
            //--------------还有用户没有添加-------------------------
            dicRelation.RELATION_ID = Guid.NewGuid().ToString();
            dicRelation.SOURCE_DICTIONARY_ID = sourceID;
            dicRelation.DESTINATION_DICTIONARY_ID = desID;
            dicRelation.RELATION_TYPE = "ROLE";
            dicRelation.CREATE_DATE = DateTime.Now;
            return dicRelation;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            List<DictionaryRelationEntity> DictionaryRelationList = ViewState["DictionaryRelationList"] as List<DictionaryRelationEntity>;
            if (DictionaryRelationList != null && DictionaryRelationList.Count > 0)
            {
                DictionaryService.DeleteRelationDictionaryByID(DictionaryRelationList[0].SOURCE_DICTIONARY_ID, "ROLE");
                DictionaryService.InsertDictionaryRelation(DictionaryRelationList);
            }
        }
    }
}